import React from 'react';
import Toast from 'antd-mobile/lib/toast';
import Modal from 'antd-mobile/lib/modal';
import isSroll from 'iscroll/build/iscroll-probe';
// import ListView from 'shared/components/ListView/list';
import classNames from 'classnames';
import { alipayApi, wxpayApi, checkPaymentStatusApi } from 'shared/api';
import callWeixinJSbridge from 'shared/utils/callWeixinJSbridge';
import { wxpayh5Pay } from 'shared/commonFetch';
import localstorage from 'shared/utils/localStorage';
import OrderDetail from '../Components/OrderDetail';
import { fetchOrderListApi } from '../api';
import './index.less';

let checkPaymentStatusTimer;

const zhifubao = require('src/static/zhifubao.png');
const weixinzhifu = require('src/static/weixinzhifu.png');

export default class Order extends React.PureComponent {
  state = {
    orderData: {
      orderlist: []
    },
    timeCount: 90,
    showAlipay: true
  }
  componentDidMount() {
    callWeixinJSbridge(this.weixinPay)
    document.querySelector('.wrapper').addEventListener('touchmove', function (e) { e.preventDefault(); }, false);
    this.fetchOrderList()
    this.initPagination();
  }

  componentWillUnmount() {
    window.clearTimeout(this.checkPaymentCount);
    window.clearInterval(this.timeOver);
  }

  weixinPay = () => {
    this.setState({ showAlipay: false });
    console.log('weixin h5 支付')
  }


  fetchOrderList(page = 1) {
    let data = {
      status:'',
    }

    if(page){
      data.page = page
    }

    Toast.loading('数据加载中', 5)
    fetchOrderListApi(data).then(({ code, data }) => {
      if (code === 1000) {
        Toast.hide();
        let { orderlist } = this.state.orderData;
        orderlist = orderlist.concat(data.orderlist);
        this.totalpage = data.totalpage;
        this.page = data.page;
        if (orderlist.length < data.limit) {
          this.setState({ showloadAllMessage: true })
        }

        this.setState({ orderData: { ...this.state, orderlist } }, () => {
          this.scroll.refresh();
        } );
      }
    })
  }

  initPagination() {
    this.scroll = new isSroll('.wrapper', {
      click: true,
      tap: true,
      probeType: 2,
    });

    this.scroll.on('scrollEnd', () => {
      if (this.totalpage === this.page && !this.state.showloadAllMessage) {
        this.setState({ showloadAllMessage: true }, () => {
          this.scroll.refresh();
        })
        return;
      }

      if (this.scroll.y - 400 < this.scroll.maxScrollY && this.totalpage > this.page) {
        this.onEndReached()
      }
    });
  }

  checkPaymentStatus(orderId) {
    checkPaymentStatusApi(orderId).then((res) => {
      if (res.code === 1000 && res.data.ispaid) {
        window.clearTimeout(checkPaymentStatusTimer);
        this.fetchOrderList()
        this.onClose();
      }
    })
  }

  onShowPaymentModal = ({ order_id, payment_method }) => {
    this.order_id = order_id;
    this.setState({ showSelectPayModal: true, payment_method })
  }

  handleSelectPaymentWay = (value) => {
    this.setState({ payment_method: value });
  }

  handlCheckout = () => {
    const { payment_method } = this.state;
    const orderId = { order_id: this.order_id, wxpayh5: 1 };

    Toast.loading('加载中', 10)
    if (payment_method === 'weixin') {
      const wxCode = localstorage.get('wxCode');
      // alert(wxCode)
      // 微信公众号支付
      if (wxCode) {
        wxpayh5Pay({ order_id: this.order_id, code: wxCode })
        return;
      }
      wxpayApi(orderId).then((res) => {
        Toast.hide();
        if (res.code === 1000) {
          this.setState({ wxUrl: res.data.wxpayh5url }, () => {
            document.querySelector("#open-wx").click()
          })
          // this.timeOver = window.setInterval(() => {
          //   this.setState({ timeCount: a-- }, () => {
          //     if (a <= 0) {
          //       this.setState({ showWxpay: false });
          //       window.clearInterval(this.timeOver);
          //       window.clearTimeout(this.checkPaymentCount);
          //     }
          //   })
          // }, 1000);

          // this.setState({ showWxpay: true, wxpayImg: res.data.base64codeimage }, () => {
          //   checkPaymentStatusTimer = window.setInterval(() => this.checkPaymentStatus(orderId), 500);
          // });
        } else {
          Toast.fail('服务端错误', 1);
        }
      })
    } else {
      let userInfo = window.localStorage.getItem('userInfo');
      if (userInfo) {
        userInfo = JSON.parse(userInfo)
      }

      const alipayData = { orderId: this.order_id, ...userInfo };

      fetch(alipayApi(alipayData))
        .then(function (response) {
          return response.text()
        }).then(function (res) {
          const div = document.createElement('div') // 创建div
          div.innerHTML = res // 将返回的form 放入div
          div.style.opacity = 0
          document.body.appendChild(div)
          document.forms[0].submit()
        })
    }
  }

  onClose = () => {
    this.setState({ showWxpay: false });
    window.clearInterval(this.timeOver);
  }

  onSelectPayModalClose() {
    this.setState({ showSelectPayModal: false })
  }

  renderItem = (item, key) => {
    return (
      <OrderDetail key={key} type="myorder" item={item} toPay={this.onShowPaymentModal} />
    );
  }

  onEndReached = () => {
    const nextPage = this.page + 1;
    this.fetchOrderList(nextPage)
  }

  render() {
    const { orderData, wxpayImg, timeCount, payment_method, wxUrl, showAlipay } = this.state;
    return (
      <div className="account-block order-block">
        <a href={wxUrl} id="open-wx" style={{ display: 'none' }} >openWx</a>
        <div className="account-block__title">
          我的订单
        </div>
        <div className="account-block__content">
          {/* {
              orderData.orderlist.map((item, index) => (
                <li key={index}><OrderDetail type="myorder" item={item} toPay={this.onShowPaymentModal} /></li>
              ))
            } */}
          <div className="list-box">
            <div className="wrapper">
              <div className="scroller">
                {
                  orderData.orderlist.map((item, index)=> <OrderDetail key={index} type="myorder" item={item} toPay={this.onShowPaymentModal} />)
                }
                {
                  this.state.showloadAllMessage &&
                  <div className="load-all" key="all">
                    <div>{orderData.orderlist.length ? '全部加载完毕' : '暂无订单'}</div>
                  </div>
                }
              </div>
            </div>

            {/* <ListView
              height={orderData.orderlist.length * 150}
              data={orderData.orderlist}
              renderItem={this.renderItem}
              onEndReached={this.onEndReached}
              hasMore={orderData.orderlist.length < this.total}
            /> */}
          </div>

        </div>
        <Modal
          visible={this.state.showSelectPayModal}
          transparent
          maskClosabl
          className="order-payment"
          footer={[{
            text: '取消', onPress: () => {
              this.onSelectPayModalClose()
            }
          },
          {
            text: '确定', onPress: () => {
              this.onSelectPayModalClose()
              this.handlCheckout()
            }
          }
          ]}
          onClose={this.onClose}
          title="选择支付方式"
        >
          <div className="payment-way">
            <div
              className={classNames('payment-way-weixin', { active: payment_method === 'weixin' })}
              onClick={() => {this.handleSelectPaymentWay('weixin')}}
            >
              <img src={weixinzhifu} alt='' />
            </div>
            {
              showAlipay &&
              <div
                className={classNames('payment-way-zhifubao', { active: payment_method === 'alipay' })}
                onClick={() => {this.handleSelectPaymentWay('alipay')}}
              >
                <img src={zhifubao} alt='' />
              </div>
            }

          </div>
        </Modal>

        <Modal
          visible={this.state.showWxpay}
          transparent
          maskClosabl
          footer={[{
            text: '关闭支付', onPress: () => {
              window.clearInterval(this.timeOver);
              window.clearTimeout(checkPaymentStatusTimer);
              this.onClose()
            }
          }]}
          onClose={this.onClose}
          title="微信支付"
        >
          <div>
            <p>请在{timeCount}内支付</p>
            <img src={wxpayImg} alt="" />
          </div>
        </Modal>
      </div>
    )
  }
}